﻿using System;

namespace Nirvana
{
    public sealed class NetReceiveBody
    {
        private byte[] Bodys;
        private int offset;
        private int curBodylength;

        public NetReceiveBody(int size)
        {
            this.Bodys = new byte[size];
            this.offset = 0;
            this.curBodylength = 0;

        }

        public byte[] GetBody()
        {
            return this.Bodys;
        }

        public int GetOffset()
        {
            return this.offset;
        }

        public int GetBodyLength()
        {
            return this.curBodylength - this.offset;
        }
        public int Copy(int length)
        {
            if (this.Bodys.Length - this.curBodylength < length)
            {
                this.ResetCopy(this.GetBodyLength() + length);
            }
            return this.curBodylength;
        }

        /// <summary>
        /// 是否存储空间有空余
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public bool IsHaveEmpty(int length)
        {
            this.curBodylength += length;
            if (this.curBodylength > this.Bodys.Length)
            {
                this.curBodylength = this.Bodys.Length;
                return false;
            }
            return true;
        }

        public void SetOffset(int length)
        {
            this.offset += length;
            if (this.offset >= this.curBodylength) //接收数据已读到当前包体长度，则复位
            {
                this.offset = 0;
                this.curBodylength = 0;
            }
        }

        public void ResetCopy(int length)
        {
            if (this.Bodys.Length - this.offset >= length)
            {
                int num = this.GetBodyLength();
                Array.Copy(this.Bodys, this.offset, this.Bodys, 0, num);
                this.offset = 0;
                this.curBodylength = num;
            }
            else
            {
                int num2 = Math.Min(this.Bodys.Length * 2, length);
                byte[] array = new byte[num2];
                int num3 = this.GetBodyLength();
                Array.Copy(this.Bodys, this.offset, array, 0, num3);
                this.Bodys = array;
                this.offset = 0;
                this.curBodylength = num3;
            }
        }

    }
}